package com.harmonk.firstscene.ui

import android.app.Application
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.harmonk.firstscene.R
import com.harmonk.firstscene.db.entity.TrafficEvent
import com.harmonk.firstscene.ui.component.EventBrief
import com.harmonk.firstscene.ui.model.RoadViewModel
import com.harmonk.firstscene.ui.model.RoadViewModelFactory
import com.harmonk.firstscene.ui.model.TrafficEventViewModel
import com.harmonk.firstscene.ui.model.TrafficEventViewModelFactory

@Composable
fun HomeScreen(
    viewModel: TrafficEventViewModel = viewModel(
        factory = TrafficEventViewModelFactory(LocalContext.current.applicationContext as android.app.Application)
    ),
    onEventClick: (TrafficEvent) -> Unit = {},
    onDeleteEvent: (TrafficEvent) -> Unit = {}
) {
    val trafficEvents by viewModel.trafficEvents.observeAsState(emptyList())

    LaunchedEffect(Unit) {
        viewModel.loadTrafficEvents()
    }

    Image(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp)
            .clip(RoundedCornerShape(16.dp)),
        painter = painterResource(id = R.drawable.banner),
        contentDescription = "Banner",
    )

    if (trafficEvents.isEmpty()) {
        EmptyState()
    } else {
        TrafficEventList(
            trafficEvents = trafficEvents,
            onEventClick = onEventClick,
            onDeleteEvent = onDeleteEvent
        )
    }
}

@Composable
fun EmptyState() {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(color = MaterialTheme.colorScheme.background)
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = "暂无现场记录，点击右下角按钮开始记录",
            modifier = Modifier.padding(16.dp)
        )
    }
}

@Composable
fun TrafficEventList(
    trafficEvents: List<TrafficEvent>,
    modifier: Modifier = Modifier,
    onEventClick: (TrafficEvent) -> Unit = {},
    onDeleteEvent: (TrafficEvent) -> Unit = {}
) {
    val roadViewModel: RoadViewModel = viewModel(
        factory = RoadViewModelFactory(LocalContext.current.applicationContext as Application)
    )
    val roads by roadViewModel.roads.observeAsState(emptyList())
    LaunchedEffect(Unit) {
        roadViewModel.loadAllRoads()
    }

    Text(
        modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
        text = "${trafficEvents.size}条记录",
        style = MaterialTheme.typography.titleSmall
    )
    LazyColumn(
        modifier = modifier
            .fillMaxSize()
            .padding(horizontal = 6.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        items(trafficEvents) { event ->
            EventBrief(
                trafficEvent = event,
                road = roads.find { it.roadId == event.roadId },
                modifier = Modifier
                    .fillMaxWidth(),
                onEventClick = onEventClick,
                onDeleteEvent = onDeleteEvent
            )
        }
    }
}

@Preview(showBackground = true)
@Composable
fun HomeScreenPreview() {
    val sampleEvents = listOf(
        TrafficEvent(
            eventId = 1L,
            timestamp = System.currentTimeMillis(),
            location = "京沪高速北京段",
            brief = "两车追尾事故",
            haveVehicleDamage = true,
            haveInjuries = false,
            haveRoadPropertyLoss = false,
            haveGoodsLoss = false,
            haveRescueExpenses = false
        ),
        TrafficEvent(
            eventId = 2L,
            timestamp = System.currentTimeMillis() - 3600000,
            location = "京港澳高速河北段",
            brief = "货车侧翻",
            haveVehicleDamage = true,
            haveInjuries = true,
            haveRoadPropertyLoss = true,
            haveGoodsLoss = true,
            haveRescueExpenses = false
        )
    )

    TrafficEventList(trafficEvents = sampleEvents)
}